package org.dralee.springsecurity.controllers;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonNode;
import org.dralee.springsecurity.models.ApiResult;
import org.dralee.springsecurity.models.LoginModel;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.jackson.JsonObjectDeserializer;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author jackielee
 * @version 1.0
 * @description HomeController
 * @date 2021/3/29
 **/
@Controller
public class HomeController {

    private final Logger logger = LoggerFactory.getLogger(HomeController.class);

    @RequestMapping("/")
    public String index(){
        return "index";
    }

    @RequestMapping("/login")
    public String login(){
        JSONObject object = new JSONObject();
        try {
            object.put("name", "lee");
            object.put("age", 20);

            int age = object.getInt("age");
            logger.info("age:"+age);
        } catch (JSONException e) {
            e.printStackTrace();
            logger.error(e.getMessage(), e);
        }
        return "login";
    }

    @PostMapping(value = "/dologin", produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public ApiResult login(@RequestBody LoginModel model, HttpServletRequest request) throws ServletException {
        if(model.getUsername() == "admin" && model.getPassword() == "123456"){
            return ApiResult.success("admin login successfully");
        }
        if(model.getUsername() == "lee" && model.getPassword() == "123456"){
            request.login(model.getUsername(), model.getPassword());
            return ApiResult.success("user login successfully");
        }
        return ApiResult.failure(403, "login failure, not a user.");
    }
}
